<template>
  <section class="component config-base">
    <el-card header="规则基本信息">
      <el-form ref="form" :rules="rules" inline :model="model" label-width="120px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="model.name" :max-length="50" placeholder="请输入策略名称" :disabled="disabledData"></el-input>
        </el-form-item>
        <el-form-item label="策略状态" prop="strategyStatus">
          <el-select v-model="model.strategyStatus" placeholder="请选择" clearable disabled>
            <el-option v-for="{ code, name } in $dict.getDictData('StrategyStatus')" :key="code" :label="name" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行频率" prop="executionFrequency">
          <el-select v-model="model.executionFrequency" placeholder="请选择" clearable :disabled="disabledData">
            <el-option v-for="{ code, name } in $dict.getDictData('ExecutionFrequency')" :key="code" :label="name" :value="code">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="执行时间" prop="startDate">
          <el-date-picker
            v-model="model.runningTime"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item> -->
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker :disabled="disabledData" @blur="endDateblur(1)" v-model="model.startDate" type="datetime" placeholder="请选择日期" :value-format="'yyyy-MM-dd HH:mm:ss'" :picker-options="$common.datePickDisabledDate(1)"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate" v-if="model.executionFrequency==='CYCLE'">
          <el-date-picker :disabled="disabledData" @blur="endDateblur(2)" v-model="model.endDate" type="datetime" placeholder="请选择日期" :value-format="'yyyy-MM-dd HH:mm:ss'" :picker-options="$common.datePickDisabledDate(1)"></el-date-picker>
        </el-form-item>
        <el-form-item label="间隔时间" prop="intervals" v-if="model.executionFrequency==='CYCLE'">
          <el-input style="width:80px" type="number" v-model="model.intervals" :max-length="50" placeholder="请输入间隔时间" :disabled="disabledData"></el-input>
        </el-form-item>
        <!-- <el-form-item prop="timeType" v-if="model.executionFrequency==='CYCLE'"> -->
        <el-select v-if="model.executionFrequency==='CYCLE'" :disabled="disabledData" style="width:80px" class="types" v-model="model.timeType" placeholder="请选择间隔时间类型" clearable>
          <el-option label="小时" value="HOURS"></el-option>
          <el-option label="天" value="DAY"></el-option>
        </el-select>
        <!-- </el-form-item> -->
        <el-form-item v-if="model.executionFrequency==='CYCLE'">
          <el-popover :disabled="showpopover" placement="left" width="300" trigger="click" height="800">
            <div style="max-height: 800px;overflow-y: scroll;">
              <h4>执行频次</h4>
              <p v-for="(item,index) of dateArr || []" :key="index">
                <span>{{`第${index+1}次执行时间：`}}</span><span>{{item}}</span>
              </p>
            </div>
            <el-button type="text" style="margin-left: 5px;" @click="viewClick()" v-if="!disabledData" slot="reference">预览频次</el-button>
          </el-popover>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header" class="row between-span">
        <span>策略取数案件池</span>
      </div>
      <el-select style="width:220px;margin-left:120px" multiple collapse-tags v-model="model.casePoolTypes" placeholder="请选择" clearable :disabled="disabledData">
        <el-option v-for="{ code, name } in $dict.getDictData('CasePoolType').slice(0,2)" :disabled="!getIsDisabled" :key="code" :label="name" :value="code">
        </el-option>
        <el-option v-for="{ code, name } in $dict.getDictData('CasePoolType').slice(2)" :disabled="!isDisabled" :key="code" :label="name" :value="code">
        </el-option>
      </el-select>
    </el-card>
    <el-card>
      <div slot="header" class="row between-span">
        <span>设置获取数据规则</span>
        <el-button @click="addNewConfigLine" v-if="!disabledData&&show||(val==='READY')">增加</el-button>
      </div>
      <expression-base v-model="strategyDataSet" :flag='false' :disabledData="disabledData" :val="val" :show="show"></expression-base>
    </el-card>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Model } from "vue-property-decorator";
import ExpressionBase from "./expression-base.vue";
import { IstrategyInfo } from "./strategy-helper.config"
import { Form } from "element-ui"
import { ValidatorService } from "~/utils/validator.service";
import { FilterService } from '~/utils/filter.service';

@Component({
  components: {
    ExpressionBase
  }
})
export default class ConfigBase extends Vue {

  @Model("base-change", {
    required: true,
    type: Object
  })
  private model: any

  @Prop({ type: Boolean }) private disabledData: boolean;
  @Prop({ type: String }) private val: string;
  @Prop({ type: Boolean }) private show: boolean;
  private cdate1: any = "";
  private cdate2: any = "";
  private cdate3: any = "";
  private dateArr: any = [];
  private showpopover: boolean = false
  private priorityList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


  private get strategyDataSet() {
    if (!this.model.formulaJson) return []
    return JSON.parse(this.model.formulaJson) as IstrategyInfo[]
  }

  private set strategyDataSet(value) {
    this.model.formulaJson = JSON.stringify(value)
  }

  private rules = {
    name: { required: true, message: "请输入策略名称" },
    strategyStatus: { required: true, message: "请选择策略状态" },
    startDate: { required: true, message: "请选择开始时间" },
    endDate: { required: true, message: "请选择结束时间" },
    intervals: [{ required: true, message: "请输入间隔时间" }, { pattern: /^[1-9][0-9]*$/, message: '时间间隔只能为大于0的正整数' }],
    timeType: { required: true, message: "请选择间隔时间类型" },
    executionFrequency: { required: true, message: "请选择执行频率" }
  }

  private get getIsDisabled() {
    return !!(!this.model.casePoolTypes.length || (this.model.casePoolTypes.length && this.model.casePoolTypes.find(v => v === 'WAIT_DISTRIBUTION' || v === 'RECOVERED_DISTRIBUTION')))
  }

  private get isDisabled() {
    return !!(!this.model.casePoolTypes.length || this.model.casePoolTypes.find(v => v !== 'WAIT_DISTRIBUTION' && v !== 'RECOVERED_DISTRIBUTION'))
  }
  /**
   * 验证基础配置数据r
   */
  private validate() {
    const form = this.$refs.form as Form
    return Promise.all([form.validate(), this.validateExpression(), this.validateBreaketComplete()])
      .then(() => this.emitBaseChange(this.model))
      .catch(() => Promise.reject('config-base'))
  }

  @Emit('base-change')
  private emitBaseChange(v) { }

  private casePool() {
    if (!this.model.casePoolTypes.length) {
      this.$message('请选择取数案件池!')
      return false
    }
  }

  private formValidate() {
    const form = this.$refs.form as Form
    form.validate(v => {

    })
  }

  /**
   * 验证数据是否完整
   */
  private validateExpression() {
    const rules = {
      relation: { required: true, message: "请选择链接关系符" },
      variable: { required: true, message: "请选择字段" },
      symbol: { required: true, message: "请选择操作符" },
      value: { required: true, message: "缺少期望值" }
    }
    const results = this.strategyDataSet.map(v => ValidatorService.validate(v, rules))
    return Promise.all(results)
      .then(() => true)
      .catch(({ errors }) => {
        if (errors.length) this.$message(errors[0].message)
        return Promise.reject(false)
      })
  }
  private endDateblur(val) {
    if (this.model.startDate && this.model.endDate && this.model.startDate > this.model.endDate) {
      if (val === 1) {
        this.$message('开始日期不能大于结束日期')
        this.model.startDate = ''
      } else {
        this.model.endDate = ''
        this.$message('结束日期不能小于开始日期')
      }
      return
    }
  }

  /**
   * 验证连接符是否完整
   */
  private validateBreaketComplete() {
    if (!this.model.casePoolTypes.length) {
      this.$message('请选择取数案件池!')
      return Promise.reject('Error')
    }
    if (!this.strategyDataSet.length) {
      this.$message('请配置数据规则')
      return Promise.reject('Error')
    }
    const result = this.strategyDataSet.reduce((s, c: IstrategyInfo) => {
      if (c.leftBracket === '(') s += 1
      if (c.leftBracket === '((') s += 2
      if (c.rightBracket === ')') s -= 1
      if (c.rightBracket === '))') s -= 2
      return s
    }, 0)

    if (result === 0) {
      return Promise.resolve(true)
    } else {
      const message = result > 0 ? '缺少右括号 ）' : '缺少左括号（'
      this.$message(message)
      return Promise.reject('Error')
    }
  }


  private addNewConfigLine() {
    let addFlag = true;
    if (this.strategyDataSet.length) {
      const lastLine = this.strategyDataSet[this.strategyDataSet.length - 1]
      addFlag = !!lastLine.relation
    }
    if (addFlag) {
      this.strategyDataSet.push({
        relation: "",
        variable: "",
        symbol: "",
        leftBracket: "",
        rightBracket: "",
        value: ""
      })
    } else {
      this.$message.warning("请完善数据规则")
    }
  }

  /**
   * 重置
   */
  private reset() {
    const form: any = this.$refs["form"];
    form.resetFields();
  }
  /**
   * 预览频次
   */
  private viewClick() {
    this.dateArr = []
    if (!this.model.startDate) {
      this.$message.warning('请先选择开始时间！')
      return
    }
    if (!this.model.endDate) {
      this.$message.warning('请先选择结束时间！')
      return
    }
    if (!this.model.timeType) {
      this.$message.warning('请先选择时间间隔类型！')
      return
    }
    if (!this.model.intervals) {
      this.$message.warning('请先选择间隔时间！')
      return
    }
    const ff: any = this.model.timeType === 'DAY' ? (Number(this.model.intervals) * 24 * 60 * 60 * 1000) : (Number(this.model.intervals) * 60 * 60 * 1000)
    let startDate: any = new Date(this.model.startDate)
    startDate = startDate.valueOf()
    let endDate: any = new Date(this.model.endDate)
    endDate = endDate.valueOf()
    if (endDate - startDate < ff) {
      this.showpopover = true
      this.$message.warning('当前策略执行时间不规范')
      this.model.intervals = ''

    } else {
      this.dateArr = FilterService.getAllDate(this.model.startDate, this.model.endDate, this.model.intervals, this.model.timeType)
      this.showpopover = false
    }
  }

}
</script>

<style lang="less" scoped>
.component.config-base {
  .types {
    width: 70px;
  }
}
</style>
